package com.sina.mysql.utils;

import org.hibernate.type.AbstractSingleColumnStandardBasicType;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @ClassName CodeEnumType
 * @Description:
 * @Author 段浩杰
 * @Date 2018/8/22 17:49
 * @Version 1.0
 */
public class CodeEnumType<T extends Enum<?>> extends AbstractSingleColumnStandardBasicType<T>
        implements TypeConfigurationAware {

    private static final long serialVersionUID = 5090303245115826753L;

    private static final ConcurrentMap<Class<?>,CodeEnumType<?>> INSTANCE_MAP = new ConcurrentHashMap<>(  );


    private TypeConfiguration typeConfiguration;


    private final Class<T> type;



    public CodeEnumType(Class<T> type) {
        super(  org.hibernate.type.descriptor.sql.IntegerTypeDescriptor.INSTANCE, new CodeEnumTypeDescriptor<>( type ) );
        this.type = type;
    }

    @Override
    public TypeConfiguration getTypeConfiguration() {
        return typeConfiguration;
    }

    @Override
    public void setTypeConfiguration(TypeConfiguration typeConfiguration) {
        this.typeConfiguration = typeConfiguration;
    }

    @SuppressWarnings( "unchecked" )
    public static  <C extends Enum<?>> CodeEnumType<C> getInstance(Class<C> clazz){
        CodeEnumType<C> type = (CodeEnumType<C>)INSTANCE_MAP.get( clazz );
        if(type == null){
            type = new CodeEnumType<>( clazz );
            INSTANCE_MAP.put( clazz,type );
        }
        return type;
    }

    @Override
    public String getName() {
        return this.getClass().getName();
    }

    @Override
    protected boolean registerUnderJavaType() {
        return true;
    }
}
